package com.htht.job.executor.util.downLoad;

import com.htht.job.executor.model.ftp.Ftp;
import org.apache.commons.net.ftp.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zzj on 2018/1/8.
 */
public class FtpUtil {
    private  FTPClient ftp;

    /**
     * Description: 向FTP服务器上传文件
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。
     * @param filename 上传到FTP服务器上的文件名
     * @param localPath    本地文件
     * @return 成功返回true，否则返回false
     */
    public  boolean uploadFile(String basePath,String filePath, String filename, String localPath) {
        boolean result = false;
        try {
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                //如果目录不存在创建目录
                String[] dirs = (basePath+filePath).split("/");
                String tempPath = "";
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            FileInputStream input=new FileInputStream(localPath);

            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            result = true;
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public  boolean downloadFile(String basePath, String localPath,String fileName,String newFileName) {
        boolean result = false;
        File file = new File(localPath+"/"+fileName+".tmp");//设置临时文件
        File localfile = new File(localPath+"/"+fileName);//设置临时文件
        try {
            if(localfile.exists()){
                result=true;
                return  result;
            }
            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            if(getIsFileExists(file)){
                long size = getSize(basePath);
                long localFileSize = getSize(file);
                if(localFileSize > size){
                    return false;
                }
                OutputStream is = new FileOutputStream(file,true);
                ftp.setRestartOffset(localFileSize);
                ftp.retrieveFile(basePath+"/"+fileName, is);
                is.close();
            }else {
                OutputStream is = new FileOutputStream(file);
                ftp.retrieveFile(basePath+"/"+fileName, is);
                is.close();
            }
            file.renameTo(new File(localPath+"/"+newFileName));
            result = true;
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return result;
    }


    public  boolean connectFtp(Ftp f) throws Exception{
        ftp=new FTPClient();
        boolean flag=false;
        int reply;
        if (f.getPort()==null) {
            ftp.connect(f.getIpAddr(),21);
        }else{
            ftp.connect(f.getIpAddr(),f.getPort());
        }
        ftp.login(f.getUserName(), f.getPwd());
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return flag;
        }
        ftp.changeWorkingDirectory(f.getPath());
        flag = true;
        return flag;
    }

    public  void closeFtp(){
    	if (null != this.ftp && this.ftp.isConnected()) {
			try {
				boolean reuslt = this.ftp.logout();// 退出FTP服务器
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					this.ftp.disconnect();// 关闭FTP服务器的连接
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    }
    /**
     * 根据文件名规则获取指定目录下的文件列表
     *
     * @param path    文件目录
     * @param pattern 文件名规则
     * @return
     * @throws IOException
     */
    public  List<String> getDataFileList(String path, final String pattern) throws IOException {
        List<String> filelist = new ArrayList<String>();
        FTPFile[] list = ftp.listFiles(path, new FTPFileFilter() {
            @Override
            public boolean accept(FTPFile file) {
                Pattern p = Pattern.compile(pattern);
                if (file.isFile() && p.matcher(file.getName()).find()) return true;
                return false;
            }
        });
        for(FTPFile ftpFile : list){
            filelist.add(ftpFile.getName());
        }
        return filelist;
    }

    public   boolean getIsFileExists(File file) {
        boolean flag = false;
        if (file.exists()) {
            flag = true;
        }
        return flag;
    }

    public   long getSize(File file) {
        long size = 0;
        if (getIsFileExists(file)) {
            size = file.length();
        }
        return size;
    }
    public   long getSize(String fileNamepath) throws IOException{
        FTPFile[] s = ftp.listFiles(new String(fileNamepath.getBytes(),ftp.getControlEncoding()));
        return s.length==0 ? 0 : s[0].getSize();

    }
    public static void main(String[] args) throws Exception{
        String str = "2015/07/20 11_02 来源: 测试";
        String regex = "\\d{4}[-|/]\\d{2}[-|/]\\d{2}";
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(str);
        String aa="";
        //.out.println("ReplaceAll:" + matcher.replaceAll("favour"));
        if (matcher.find()) {
            aa=matcher.group();
        }
        Pattern p1 = Pattern.compile("\\{.*.}");
        Matcher matcher1 = p1.matcher("aa{yyyyy}aa");
        String pp=matcher1.replaceAll(aa);
        System.out.print(pp);
        String regex1=".+?\\.([a-zA-z]+)$";
        Pattern pt=Pattern.compile(regex1);
        Matcher mt=pt.matcher("bbb.bb.tif");
        if(mt.find())
        {
            System.out.println(mt.group());
        }
       /* Ftp f=new Ftp();
        f.setUserName("zzj");
        f.setPwd("root");
        f.setIpAddr("10.37.129.5");
        FtpUtil ftpUtil=new FtpUtil();
        ftpUtil.connectFtp(f);
        ftpUtil.uploadFile("/home/zzj/","zzj","aa.sh","/zzj/test.sh");

        List<String> list=ftpUtil.getDataFileList("/home/zzj/Desktop/zk/zookeeper-3.3.6/","");
        for (String name:list){
            ftpUtil.downloadFile("/home/zzj/Desktop/zk/zookeeper-3.3.6/"+name,"/zzj/ftp/ftp/",name,name);
        }*/
    }
    }